package org.jflame.captcha;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.concurrent.ThreadLocalRandom;

public final class CaptchaUtils {

    /**
     * 默认验证码图片格式
     */
    public static String default_img_ext = "png";

    public static Color getRandColor() {
        return getRandColor(0, 255);
    }

    public static Color getRandColor(int start, int end) {
        if (start < 0) {
            start = 0;
        }
        if (start > 255) {
            start = 200;
        }
        if (end < 0 || end > 255) {
            end = 255;
        }
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return new Color(random.nextInt(start, end), random.nextInt(start, end), random.nextInt(start, end));
    }

    public static int nextInt(int bound) {
        return ThreadLocalRandom.current()
                .nextInt(bound);
    }

    /**
     * 图片覆盖（覆盖图压缩到width*height大小，覆盖到底图上）
     *
     * @param baseBufferedImage 底图
     * @param coverBufferedImage 覆盖图
     * @param x 起始x轴
     * @param y 起始y轴
     */
    public static void overlayImage(BufferedImage baseBufferedImage, BufferedImage coverBufferedImage, int x, int y) {
        // 创建Graphics2D对象，用在底图对象上绘图
        Graphics2D g2d = baseBufferedImage.createGraphics();
        // 绘制
        g2d.drawImage(coverBufferedImage, x, y, coverBufferedImage.getWidth(), coverBufferedImage.getHeight(), null);
        // 释放图形上下文使用的系统资源
        g2d.dispose();
    }

}
